package cn.pku.ss.fa.sessionbean;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import cn.pku.ss.fa.entity.*;

import java.util.*;

import cn.pku.ss.fa.bean.*;
import cn.pku.ss.fa.entity.events.*;


@Stateless
public class AlbumManager implements AlbumManagerLocal {

	@PersistenceContext
	protected EntityManager manager;
	
    public int createAlbum(AlbumBean albumBean) {
    	User user = manager.find(User.class, albumBean.getUserId());
		if (user == null)
			return Integer.MIN_VALUE;
		
		Album album = new Album();
		album.setCreateTime(new Date());
		album.setDescription(albumBean.getDescription());
		album.setName(albumBean.getName());
		album.setPath(albumBean.getURL());
		album.setUser(user);
		
	   try {
		user.getAlbums().add(album);
		manager.persist(album);
	   } catch (Exception e) {
		   e.printStackTrace();
		   return Integer.MIN_VALUE;
	   }
		
	   //Notify the user's friends of this album creating event
	   Set<User> friends = user.getFriends();
	   for (Iterator iter = friends.iterator(); iter.hasNext(); ) {
		   User friend = (User)iter.next();
		   AlbumReminder albumReminder = new AlbumReminder();
		   albumReminder.setAlbumId(album.getId());
		   albumReminder.setAlbumName(album.getName());
		   albumReminder.setFriendId(friend.getId());
		   albumReminder.setHostId(user.getId());
		   albumReminder.setHostRealName(user.getRealName());
		   albumReminder.setCreateTime(new Date());
		   manager.persist(albumReminder);
	   }
	   
		return album.getId().intValue();
		
	}
    
    public List<AlbumBean> getAlbumsList(int userId) {
    	User user = manager.find(User.class, userId);
		if (user == null)
			return null;
		
		List<AlbumBean> albumBeans = new ArrayList<AlbumBean>();
		Set<Album> albums = user.getAlbums();
		for (Iterator iter = albums.iterator(); iter.hasNext(); ) {		                                                           
			Album album = (Album)iter.next();
			AlbumBean albumBean = this.convertAlbumToAlbumBean(album);
			albumBeans.add(albumBean);
		}
		return albumBeans;
		
    }
    
    private AlbumBean convertAlbumToAlbumBean(Album album) {
    	User user = album.getUser();
    	AlbumBean albumBean = new AlbumBean();
    	albumBean.setDescription(album.getDescription());
    	albumBean.setId(album.getId());
    	albumBean.setName(album.getName());
    	albumBean.setURL(album.getPath());
    	albumBean.setUserId(user.getId());
    	albumBean.setUserRealName(user.getRealName());
    	
    	List<PhotoBean> photoBeans = new ArrayList<PhotoBean>();
    	Set<Picture> pictures = album.getPictures();
    	
    	for (Iterator iter = pictures.iterator(); iter.hasNext(); ) {
    		Picture picture = (Picture)iter.next();
    		PhotoBean photoBean = this.convertPictureToPhotoBean(picture);
    		photoBeans.add(photoBean);
    	}
    	
    	albumBean.setPhotos(photoBeans);
    	
    	return albumBean;
    }
    
    public PhotoBean getPhotoBean(int photoId) {
    	Picture picture = manager.find(Picture.class, photoId);
    	
    	return this.convertPictureToPhotoBean(picture);
    }
    
    private PhotoBean convertPictureToPhotoBean(Picture picture) {
    	PhotoBean photoBean = new PhotoBean();
		photoBean.setDescription(picture.getDescription());
		photoBean.setId(picture.getId());
		photoBean.setName(picture.getName());
		photoBean.setURL(picture.getPath());
		photoBean.setAlbumId(picture.getAlbum().getId());
		
		
		return photoBean;
    }
    
    public void updatePhotoName(int photoId, String newName) {
    	Picture picture = manager.find(Picture.class, photoId);
    	picture.setName(newName);
    }
    
    public void updatePhotoDescription(int photoId, String newDescription) {
    	Picture picture = manager.find(Picture.class, photoId);
    	picture.setDescription(newDescription);
    }
    
    public List<AlbumNewsBean> getAlbumNewsList(int userId) {
    	Query query1 = manager.createQuery("select p from AlbumReminder p where p.friendId = ?1 ");
		Query query2 = manager.createQuery("select p from PictureReminder p where p.friendId = ?1 ");
    	query1.setParameter(1, userId);
    	query2.setParameter(1, userId);
		
		List albumCreatingEvents = query1.getResultList();
		List photoUploadingEvents = query2.getResultList();
		
		
		List<AlbumNewsBean> newsBeans = new ArrayList<AlbumNewsBean>();
		
		for (Iterator iter = albumCreatingEvents.iterator(); iter.hasNext(); ) {
			AlbumReminder albumReminder = (AlbumReminder)iter.next();
			AlbumNewsBean newsBean = new AlbumNewsBean();
			newsBean.setType(AlbumNewsBean.TYPE_CREATE_ALBUM);
			newsBean.setAlbumName(albumReminder.getAlbumName());
			newsBean.setDate(String.valueOf(albumReminder.getCreateTime()));
			newsBean.setUserId(albumReminder.getHostId());
			newsBean.setUserName(albumReminder.getHostRealName());
		    newsBeans.add(newsBean);
		}
		
		for (Iterator iter = photoUploadingEvents.iterator(); iter.hasNext(); ) {
			PictureReminder pictureReminder = (PictureReminder)iter.next();
			AlbumNewsBean newsBean = new AlbumNewsBean();
			newsBean.setType(AlbumNewsBean.TYPE_UPLOAD_PHOTO);
			newsBean.setDate(String.valueOf(pictureReminder.getCreateTime()));
			newsBean.setAlbumName(pictureReminder.getAlbumName());
			newsBean.setUserId(pictureReminder.getHostId());
			newsBean.setUserName(pictureReminder.getHostRealName());
			newsBeans.add(newsBean);
		}
		return newsBeans;
    }
    
    public int createPhoto(int userId, PhotoBean photoBean) {
    	Picture picture = new Picture();
    	try {
    	Album album = manager.find(Album.class, photoBean.getAlbumId());
    	
    	picture.setDescription(photoBean.getDescription());
    	picture.setName(photoBean.getName());
    	picture.setPath(photoBean.getURL());
    	picture.setUploadTime(new Date());
    	
        album.getPictures().add(picture);
        picture.setAlbum(album);
        manager.persist(picture);
        
        //Generate photo uploading event
        User user = manager.find(User.class, userId);
        Set<User> friends = user.getFriends();
 	   for (Iterator iter = friends.iterator(); iter.hasNext(); ) {
 		   User friend = (User)iter.next();
 		   PictureReminder pictureReminder = new PictureReminder();
 		   pictureReminder.setAlbumId(album.getId());
 		   pictureReminder.setAlbumName(album.getName());
 		   pictureReminder.setFriendId(friend.getId());
 		   pictureReminder.setHostId(user.getId());
 		   pictureReminder.setHostRealName(user.getRealName());
 		   pictureReminder.setCreateTime(new Date());
 		   
 		   manager.persist(pictureReminder);
 	   }
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
        
        return picture.getId().intValue();
    }
}
